<!--
  -    公表管理
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @on-load="getList"
        @row-del="rowDel"
        @search-reset="SearchReset"
        @search-change="searchChange"
        @refresh-change="refreshChange"
      >
        <template
          slot-scope="scope"
          slot="projectBuildingIdSearch"
        >
          <el-select
            v-model="searchForm.projectBuildingId"
            placeholder="请选择"
            @change="projectBuildingIdChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.label=='展场'"
            >
            </el-option>
          </el-select>
        </template>
<!--        新增期数-->
        <template
          slot-scope="scope"
          slot="projectRegionStageSearch"
        >
          <el-select
            v-model="searchForm.projectRegionStage"
            placeholder="请选择期数"
            @change="projectBuildingIdChange1"
          >
            <el-option
              v-for="item in projectUnitIdOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.label=='展场'"
            >
            </el-option>
          </el-select>
        </template>
        <template
          slot-scope="scope"
          slot="writeDateSearch"
        >
          <el-date-picker
            v-model="searchForm.writeDate"
            type="month"
            placeholder="选择应缴月份"
            format='yyyy-MM'
            value-format="yyyy-MM"
          >
          </el-date-picker>
        </template>
        <template
          slot-scope="scope"
          slot="projectSiteSearch"
        >
          <el-select
            v-model="searchForm.projectUnitId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectDetaList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
        <template
          slot="menuLeft"
          slot-scope="scope"
        >
          <!-- <el-button
            v-if="meter_mrproject_add"
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            @click="addOrUpdateHandle('add','')"
          >
            新增
          </el-button> -->
          <el-button
            v-if="meter_mrproject_excport"
            class="filter-item"
            type="default"
            icon="el-icon-download"
            @click="rmEexport()"
          >
            导出
          </el-button>
          <el-button
            v-if="meter_mrproject_import"
            class="filter-item"
            type="default"
            icon="el-icon-upload2"
            @click="rmImport()"
          >
            导入
          </el-button>
        </template>
        <template
          slot="projectName"
          slot-scope="scope"
        >
          <el-link
            type="primary"
            :underline="false"
            @click="handleView('view',scope.row.id)"
          >{{scope.row.projectName}}</el-link>
        </template>
        <template
          slot="menu"
          slot-scope="scope"
        >
          <el-button
            v-if="meter_mrproject_get"
            type="text"
            @click="handleView('view',scope.row)"
          >
            查看
          </el-button>
          <!-- <el-button
            v-if="meter_mrproject_del"
            type="text"
            @click="rowDel(scope.row,scope.index)"
          >
            清除
          </el-button> -->
        </template>
      </avue-crud>

      <table-form
        v-if="addOrUpdateVisible"
        ref="addOrUpdate"
        @refreshDataList="getList"
      ></table-form>
      <table-forms
        v-if="viewVisible"
        ref="viewBtn"
        @refreshDataList="getList"
      ></table-forms>
      <!--导入-->
      <el-dialog
        title="批量导入"
        :visible.sync="uploadlg.show"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="500px"
        :before-close="BeforeClose"
      >
        <el-button
          style="color:#409EFF;"
          @click="onDowmload"
        >下载填充数据</el-button>
        <br>
        <br>
        <el-upload
          ref="upload"
          class="upload-box"
          drag
          action=""
          :http-request="HttpRequest"
          :auto-upload="false"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          name="files"
          :before-upload="beforeUpload"
          :data="uploadlg.extraData"
          :on-change="changeUpload"
          :on-remove="reMoveUpload"
          :on-success="uploadSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择导入文件</em></div>
        </el-upload>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            @click="submitFile"
          >导入</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, ImportFile } from '@/api/market/meter/Private/person'
import { tableOption } from '@/const/crud/market/meter/Private/person'
import TableForm from './Form'
import TableForms from './FormModify'
import { mapGetters } from 'vuex'
import { getDicType, ExportFile } from '@/api/common'
export default {
  name: 'Private',
  components: { TableForm, TableForms },
  data () {
    return {
      // 导出模板
      importform: {
        projectBuildingId: '',
        projectUnitId: '',
        getRecordDetails: '',
        meterType: ''
      },
      searchForm: {
        projectBuildingId: '',
        projectUnitId: '',
        writeDate: '',
        projectRegionStage:''
      },
      projectUnitList: [],
      tableData: [],
      addOrUpdateVisible: false,
      viewVisible: false,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      meter_mrproject_get: false,
      meter_mrproject_add: false,
      meter_mrproject_edit: false,
      meter_mrproject_del: false,
      meter_mrproject_excport: false,
      meter_mrproject_import: false,
      options: [],
      projectUnitIdOptions: [],
      projectDetaList:[],        //期数
      uploadlg: {
        show: false,
        noUploadFile: true
      },
      rules: {
        writeDate: [
          { required: true, message: "请选择应缴月份", trigger: "change" }
        ],
        projectBuildingId: [
          { required: true, message: "请选择房屋类型", trigger: "change" }
        ],
        projectUnitId: [
          { required: true, message: "请选择房产楼号/区域", trigger: "change" }
        ],
        meterDate: [
          { required: true, message: "请选择抄表时间", trigger: "change" }
        ],
        meterType: [
          { required: true, message: "请选择公表类型", trigger: "change" }
        ],
        unitPrice: [
          { required: true, message: "请选择公摊单价", trigger: "blur" }
        ]
      }
    }
  },
  created () {
    this.meter_mrproject_get = this.permissions['meter_mrproject_get']
    this.meter_mrproject_add = this.permissions['meter_mrproject_add']
    this.meter_mrproject_edit = this.permissions['meter_mrproject_edit']
    this.meter_mrproject_del = this.permissions['meter_mrproject_del']
    this.meter_mrproject_excport = this.permissions['meter_mrproject_excport']
    this.meter_mrproject_import = this.permissions['meter_mrproject_import']
    let currdate = new Date()
    let currmonth = '0' + (currdate.getMonth() + 1)
    this.searchForm.writeDate = currdate.getFullYear() + "-" + currmonth.substring(currmonth.length - 2)
  },
  mounted () {
    getDicType('rm_project_buiding_type').then(res => {
      this.options = res.data.data
    })

  },
  computed: {
    ...mapGetters(['elements', 'permissions'])
  },
  methods: {
    onChangeTpe () {
      // if (this.importform.projectBuildingId == 2) {
      //   this.getfoolerOptionsValue('complex_building')
      // } else if (this.importform.projectBuildingId == 3) {
      //   this.getfoolerOptionsValue('exhibition')
      // } else if (this.importform.projectBuildingId == 1) {
      //   this.getfoolerOptionsValue('exclusive_shop')
      // }
      this.getfoolerOptionsValue(this.importform.projectBuildingId)
    },
    getfoolerOptionsValue (name) {
      getDicType(name).then(res => {
        this.importform.projectUnitId = ''
        this.projectUnitList = res.data.data
      })
    },
    SearchReset () {
      this.searchForm = {
        projectBuildingId: '',
        projectUnitId: ''
      }
      let currdate = new Date()
      let currmonth = '0' + (currdate.getMonth() + 1)
      this.searchForm.writeDate = currdate.getFullYear() + "-" + currmonth.substring(currmonth.length - 2, 2)
    },
    // 导出
    rmEexport () {
      ExportFile('/meter/mrprivatemeterwriterecord/downloadPrivateMeter', this.searchForm)
    },
    // 导入
    rmImport () {
      this.uploadlg.show = true;
      if (this.$refs.importform) {
        this.$refs.importform.resetFields();
      }
    },
    getList (page, params) {
      // this.tableData = [{ "id": "1", "projectName": "399号附22号11-7", "projectBuildingId": "1", "projectUnitId": "12", "writeDate": "2019-9-2", "totalPoint": "10", "totalPoints": "160", "meterDate": "2019-9-2", "unitPrice": "100", "meterType": "1" }];
      // this.page.total = 1;
      this.tableLoading = true
      fetchList(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    rowDel: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 查看
    handleView: function (method, row) {
      this.viewVisible = true
      this.$nextTick(() => {
        this.$refs.viewBtn.init(method, {
          projectId: row.projectId,
          projectBuildingName: row.$projectBuildingId,
          projectNumber: row.projectNumber,
          projectBuildingId: row.projectBuildingId,
          projectUnitId: row.projectUnitId,
          writeDate: row.writeDate,
          writeTime: row.writeTime,
          prjectFloorNumber: row.prjectFloorNumber
        })
      })
    },
    // 新增、修改
    addOrUpdateHandle (isEdit, id) {
      this.addOrUpdateVisible = true
      // this.$nextTick(() => {
      setTimeout(() => {
        this.$refs.addOrUpdate.init(isEdit, id)
      }, 2)
      // })
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange (current) {
      this.page.currentPage = current
    },
    searchChange (form, done) {
      // this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    },
    // 导出模块
    BeforeClose () {
      this.uploadlg.show = false
      this.$refs.upload.clearFiles()
    },
    submitFile () {
      // this.$refs['importform'].validate((valid) => {
      //   if (valid) {
      if (this.uploadlg.noUploadFile) {
        this.$message({
          type: 'warning',
          message: '请选择文件'
        })

        return
      }
      this.$refs.upload.submit()
      //   }
      // })
    },
    onDowmload () {
      // this.$refs['importform'].validate((valid) => {
      //   if (valid) {
      // ExportFile('/meter/mrprivatemeterwriterecord/downloadPrivateMeter', this.importform)
      // ExportFile('/meter/mrprivatemeterwriterecord/downloadPrivateMeter', {})
      ExportFile('/meter/mrprivatemeterwriterecord/downloadPrivateMeter', this.searchForm)
      // }
      // })
      // ExportUrlFile('/contract/template/1', {})
    },
    // 覆盖action方法，自定义上传方法
    HttpRequest (file) {
      let fromdata = new FormData()
      fromdata.append("file", file.file)
      ImportFile(fromdata).then(res => {
        if (res.data.code == 0) {
          this.uploadlg.show = false
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
          this.$refs.upload.clearFiles()
          this.getList(this.page)
        } else {
          this.$message({
            type: 'error',
            message: '导入失败!'
          })
        }
      })
    },
    beforeUpload (file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file
        .type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('导入文件格式只能上传.xlsx或.xls!')
      }

      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.warning('上传文件的大小不能超过 50M!')
      }

      return isLt50M && isExcel
    },
    handleExceed (files) {
      this.$message.warning(`当前导入限制只能上传 1 个文件`)
    },
    changeUpload (file, fileList) {
      if (fileList.length > 0) {
        this.uploadlg.noUploadFile = false
      } else {
        this.uploadlg.noUploadFile = true
      }
    },
    reMoveUpload (file, fileList) {
      if (fileList.length === 0) {
        this.uploadlg.noUploadFile = true
      }
    },
    uploadSuccess (response) {
      console.log(response)
    },
    projectBuildingIdChange (e) {
      // if (this.searchForm.projectBuildingId == 2) {
      //   this.getfoolerOptionsValues('complex_building')
      // } else if (this.searchForm.projectBuildingId == 3) {
      //   this.getfoolerOptionsValues('exhibition')
      // } else if (this.searchForm.projectBuildingId == 1) {
      //   this.getfoolerOptionsValues('exclusive_shop')
      // }
      this.projectUnitIdOptions=[]
      this.projectDetaList=[]
      this.getfoolerOptionsValues(this.searchForm.projectBuildingId)
    },
    projectBuildingIdChange1 (e){
      this.projectDetaList=[]
      this.projectUnitIdOptions=[]
      this.getfoolerOptionsValues1(e)
    },
    getfoolerOptionsValues (name) {
      getDicType(name).then(res => {
        this.searchForm.projectUnitId = ''
        this.projectUnitIdOptions = res.data.data
      })
    },
    getfoolerOptionsValues1 (name) {
      getDicType(name).then(res => {
        this.searchForm.projectUnitId = ''
        this.projectDetaList = res.data.data
      })
    },

  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-upload-dragger {
  width: 460px;
}
</style>
